import { Table, message } from 'antd';
import Cls from 'classnames';
import { AcquisitionManageContext, IAcquisitionActionEnum, useAcquisitionManageReducer } from '../mconfig';
import { useContext, useEffect, useMemo, useState } from 'react';
import { openMaterielColumns } from '../mconfig';
import { getLoadMapList, getSelectDataMapList, getTenantID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { formatDecimalFour } from '../../../Acommon';
import _ from 'lodash';
import { deleteMaterialServices } from '../services';

export const UpdateMaterielView: React.FC<any> = ({
  curRes,
  handleMaterialModal,
  isNew,
  pageType,
  handleBatchModal,
  isNowCheckPeople,
  selectType,
  pagination,
  reloadManage,
  materialToatalPrice,
  loading,
  editMaterialLoading,
  onSelectRadio,
  checkMaterialList,
  detailInfo,
}) => {
  // /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`, //类型
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //品牌
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //单位
    `${getTenantID()}${ILoadMapTypeAll.ASSET_EQUITY}`, // 产权
  ]);

  /** 引入上下文 */
  const { materielList, acquisitionDispatch, handleAssetVisible } = useContext(AcquisitionManageContext);

  /** 删除申请回调 */
  const deleteMaterialCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadManage();
    } else {
      message.error(res?.msg);
    }
  };

  /** 删除物资 */
  const { deleteMaterialRun, deleteMaterialLoading } = deleteMaterialServices(deleteMaterialCallback);

  const delSelectRow = (record) => {
    if (record?.id) {
      deleteMaterialRun(record?.id);
    } else {
      // 取消选中材料列表
      const arr = materielList.filter((item) => {
        if (item.id) {
          return item.id !== record.id;
        } else {
          return item.rowId !== record.rowId;
        }
      });
      // 更新选中的数据
      acquisitionDispatch({
        type: IAcquisitionActionEnum.SELECT_MATERIEL,
        payload: arr,
      });

      if (selectType == 1) {
        // 删除资产，清空form表单
        acquisitionDispatch({
          type: IAcquisitionActionEnum.CANCEL_FORM_INFO,
        });
        acquisitionDispatch({
          type: IAcquisitionActionEnum.SELECT_ASSET_INFO,
          payload: {},
        });
      }
    }
  };

  const handleAdd = () => {
    // 校验是否选择入库类型
    const tempType = selectType.toString();
    if (!tempType) {
      return message.warning('请选择物资类型');
    }
    const addData = {
      rowId: new Date().getTime(),
      assetjson: {
        formAddFlag: true, // 资产入库，标识是新增的
      },
    };

    acquisitionDispatch({
      type: IAcquisitionActionEnum.SELECT_MATERIEL,
      payload: [...materielList, addData],
    });

    // // 资产入库
    // if (tempType == '1') {
    //   handleAssetVisible('edit');
    // }
  };

  const editTable = (arg: any) => {
    const { type, value, index } = arg;
    const tempList = [...materielList];

    // 物资名称
    if (type == 'assetName') {
      tempList[index].assetName = value;
    }
    // 物资类型
    if (type == 'sourceTypeName') {
      tempList[index].sourceTypeName = value;
    }
    // 物资编码
    if (type == 'materialCode') {
      tempList[index].materialCode = value;
    }
    // 规格参数
    if (type == 'paramsInfo') {
      tempList[index].paramsInfo = value;
    }
    // 数量
    if (type == 'quantityOrArea') {
      tempList[index].quantityOrArea = value;
      if (tempList[index].assetValue) {
        const price = tempList[index].assetValue * 100;
        const number = tempList[index].quantityOrArea * 100;
        tempList[index].totalValue = _.round((price * number) / 10000, 4);
      }
    }
    // 量化单位
    if (type == 'unitOfMeasurement') {
      tempList[index].unitOfMeasurement = value;
    }
    // 单价
    if (type == 'assetValue') {
      tempList[index].assetValue = value;
      if (tempList[index].quantityOrArea) {
        const price = tempList[index].assetValue * 100;
        const number = tempList[index].quantityOrArea * 100;
        tempList[index].totalValue = _.round((price * number) / 10000, 4);
      }
    }
    // 类型
    if (type == 'assetClass') {
      tempList[index].assetClass = value;
    }
    // 品牌
    if (type == 'brandType') {
      tempList[index].brandType = value;
    }
    // 产权
    if (type == 'ownership') {
      tempList[index].ownership = value;
    }
    // 单位
    if (type == 'unitOfMeasurement') {
      tempList[index].unitOfMeasurement = value;
    }
    // 供应商
    if (type == 'supplier') {
      tempList[index].supplier = value?.target?.value;
      if (tempList[index].assetjson) {
        tempList[index].assetjson.supplier = value?.target?.value;
      }
    }
    acquisitionDispatch({
      type: IAcquisitionActionEnum.SELECT_MATERIEL,
      payload: tempList,
    });
  };

  /** 表格行配置 */
  const columns: Record<string, any>[] = useMemo(() => {
    return openMaterielColumns(
      loadMapInfo,
      handleMaterialModal,
      handleAdd,
      delSelectRow,
      pageType,
      selectType,
      handleAssetVisible,
      materielList,
      editTable,
      handleBatchModal,
      isNowCheckPeople,
      isNew,
      checkMaterialList,
      onSelectRadio,
      detailInfo,
    );
  }, [materielList, selectType, loadMapInfo, isNew]);

  return (
    <div className={Cls('list-table', 'descriptionsType-tableSty')} style={{ marginTop: '10px' }}>
      <Table
        bordered
        size="small"
        dataSource={materielList}
        columns={columns}
        rowKey={(res) => (res.id ? res.id : res.rowId)}
        scroll={{ x: 1200, y: '' }}
        pagination={pagination}
        loading={loading || editMaterialLoading || deleteMaterialLoading}
      />
      <div style={{ textAlign: 'right' }}>合计：&yen;{formatDecimalFour(materialToatalPrice) || '0.0000'}</div>
    </div>
  );
};
